package com.shaoshaohuo.app.ui.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.RelativeLayout;

import com.shaoshaohuo.app.R;
import com.shaoshaohuo.app.adapter.AllOrderListViewAdapter;
import com.shaoshaohuo.app.entity.OrderShopInfoEntity;
import com.shaoshaohuo.app.framework.SharedPreferencesHelper;
import com.shaoshaohuo.app.net.HttpConfig;
import com.shaoshaohuo.app.net.RequestParam;
import com.shaoshaohuo.app.ui.ItemOrderDetails;
import com.shaoshaohuo.app.utils.Okhttputils;
import com.shaoshaohuo.app.utils.ToastUtil;
import com.shaoshaohuo.app.view.LoadListView;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Response;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * to handle interaction events.
 * Use the {@link MyOrderFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class MyOrderFragment extends Fragment implements AdapterView.OnItemClickListener, AllOrderListViewAdapter.CallBackListener {
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private View view;
    // TODO: Rename and change types of parameters
    private String tabString = "";//tab标签
    private String mParam2;
    private Mybrocatrecier mybrocatrecier;
    private LoadListView all_order_listView;
    private List<OrderShopInfoEntity.DataBean> all_order_listView_data;
    private AllOrderListViewAdapter all_order_listView_adapter;


//    private SwipeRefreshLayout All_order_swip;
    /**
     * 没有订单信息的时候
     */
    private RelativeLayout no_order_relative;
    private Button no_order_guangguang;
    //    private boolean mHasLoadedOnce = false;
    private int page = 0;

    public MyOrderFragment() {
        // Required empty public constructor
    }

    public static MyOrderFragment newInstance(String param1, String param2) {
        MyOrderFragment fragment = new MyOrderFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            tabString = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_my_order, container, false);
        initView();
        bindAdapter();
        initListener();
        return view;

    }

    private void requestData() {
        Map<String, String> map_head = RequestParam.getHeaderParams();
        if (tabString != null) {
            getOrderData(map_head);
//            if (tabString.equals("全部")) {
//                getOrderData(map_head);
//            } else if (tabString.equals("待付款")) {
//                getOrderData(map_head);
//
//            } else if (tabString.equals("待发货")) {
//                getOrderData(map_head);
//
//            } else if (tabString.equals("待收货")) {
//                getOrderData(map_head);
//
//            } else if (tabString.equals("待确认")) {
//                getOrderData(map_head);
//
//            } else if (tabString.equals("已完成")) {
//                getOrderData(map_head);

//        }
        }
    }

    private void getOrderData(Map<String, String> map_head) {
        page += 1;
        Map<String, String> map_body = new HashMap<>();
        map_body.clear();
        map_body.put("type", HttpConfig.SubUrl.OrderBody(tabString));
        map_body.put("page", page + "");
        Okhttputils.Instanse(getActivity()).postFromBody(map_head, HttpConfig.BASE_HOST_URL + HttpConfig.SubUrl.SEARCH_ORDER, map_body, new Okhttputils.OkutListener() {
            @Override
            public void error(Call call, IOException e) {

            }

            @Override
            public void error(Call call, final int code) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Log.e("返回错误", code + "");
                        all_order_listView_data.clear();
                        no_order_relative.setVisibility(View.VISIBLE);
//                        All_order_swip.setVisibility(View.GONE);
                        all_order_listView.setVisibility(View.GONE);
                        all_order_listView_adapter.refreshAdapter(all_order_listView_data);
                    }
                });
            }

            @Override
            public void suseff(Call call, Response response, Object o) {
                OrderShopInfoEntity shopInfoEntity = (OrderShopInfoEntity) o;
                all_order_listView_data = shopInfoEntity.getData();
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Log.e(tabString, all_order_listView_data.size() + "=====" + page);
                        if (page == 1) {
                            all_order_listView_adapter.clearData();
                            if (all_order_listView_data.size() == 0) {
                                no_order_relative.setVisibility(View.VISIBLE);
                                all_order_listView.setVisibility(View.GONE);
                            }

                        }
                        if (all_order_listView_data.size() != 0) {
                            no_order_relative.setVisibility(View.GONE);
                            all_order_listView.setVisibility(View.VISIBLE);
                            all_order_listView_adapter.addload(all_order_listView_data);
                        }
                        if (page != 1) {
                            all_order_listView.stopload("加载完毕", true);
                        }

                    }
                });
            }
        }, OrderShopInfoEntity.class);
    }

    private void initListener() {
        all_order_listView.setOnItemClickListener(this);
        no_order_guangguang.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SharedPreferencesHelper sharedPreferencesHelper = new SharedPreferencesHelper();
                sharedPreferencesHelper.setBoolean(getActivity(), SharedPreferencesHelper.Field.HOME, true);
                getActivity().finish();
            }
        });
        all_order_listView_adapter.setCallBackListener(this);
    }

    private void bindAdapter() {
        all_order_listView.setAdapter(all_order_listView_adapter);
    }

    private void initView() {
        /**
         * 有订单信息
         * */
        all_order_listView = (LoadListView) view.findViewById(R.id.All_order_listView);
        all_order_listView.setLoadListener(new LoadListView.LoadListener() {
            @Override
            public void loadlistener() {
                requestData();
            }
        });
        all_order_listView_data = new ArrayList<>();
        all_order_listView_adapter = new AllOrderListViewAdapter(all_order_listView_data, getActivity(), tabString);
//        All_order_swip = (SwipeRefreshLayout) view.findViewById(R.id.All_order_swip);
        /**
         * 没有订单的时候
         * */
        no_order_relative = (RelativeLayout) view.findViewById(R.id.no_order_relative);
        no_order_guangguang = (Button) view.findViewById(R.id.no_order_guang);

        mybrocatrecier = new Mybrocatrecier();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("daifukuan");
        getActivity().registerReceiver(mybrocatrecier, intentFilter);
    }


    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        AllOrderListViewAdapter adapter = (AllOrderListViewAdapter) parent.getAdapter();
        List<OrderShopInfoEntity.DataBean> data1 = adapter.getData();
        if (data1.get(position).getGoodStatus().equals("2")){
            ToastUtil.toast("商品已过期");
        }else {
            Intent intent = new Intent();
            Bundle bundle = new Bundle();
            List<OrderShopInfoEntity.DataBean> data = all_order_listView_adapter.getData();
            if (data != null || data.size() > 0 && position != data.size()) {
                OrderShopInfoEntity.DataBean dataBean = data.get(position);
                int type = dataBean.getType();
//            if (type == 1) {
                intent.setClass(getActivity(), new ItemOrderDetails().newInstance(intent, dataBean, data.get(position).getStatus(), type + "", "2").getClass());
                startActivity(intent);
//            }
            }
        }

    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        Log.e("TAG", "onViewCreated");
    }


    @Override
    public void onResume() {
        super.onResume();
        page = 0;
        requestData();
    }

    @Override
    public void onStop() {
        super.onStop();
        Log.e("TAG", "onStop");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.e("TAG", "onDestroy");
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mybrocatrecier != null) {
            getActivity().unregisterReceiver(mybrocatrecier);
        }

    }

    @Override
    public void onPause() {
        super.onPause();
        Log.e("TAG", "onPause");
    }

    @Override
    public void refreshData(String type) {
        Log.e("回调", type);
//        tabString = type;
        page = 0;
        requestData();
    }

    class Mybrocatrecier extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            page = 0;
            if (action.equals("daifukuan")) {
//                String daifukuan = (String) intent.getExtras().get("daifukuan");
                Log.e("daifukuan", tabString);
                requestData();
            }
        }
    }
}
